import os
import csv
import pydub

def m4a_wav(m4a_file, wav_file):
    audio = pydub.AudioSegment.from_file(m4a_file, format = "m4a")
    audio.export(wav_file, format = "wav")

def pack_wavs(wav_files, save_to="test.wav"):
    output = None
    for wav_file in wav_files:
        wav = pydub.AudioSegment.from_wav(wav_file)
        if output == None:
            output = wav
            continue
        output += wav
    output.export(save_to, format="wav")


if __name__ == '__main__':
    input_m4a = "xy.m4a"
    wav_file = "xy.wav"
    # m4a_wav(input_m4a, wav_file)
    
    # wav_files = ["BAC009S0769W0292.wav", "BAC009S0906W0203.wav"]
    wav_files = ["BAC009S0901W0407.wav", "BAC009S0916W0426.wav"]
    # pack_wavs(wav_files)
    
            
    wav_files = "/home/gyf/pkg/conformer_new/asr_conformer/dataset/full_path.txt"
    wav_dict = {}
    with open(wav_files, "r", encoding="utf-8") as wf:
        lines = wf.readlines()
        for line in lines:
            line = line.strip().split(" ")
            wav_dict[line[0]] = line[1]
        
    file_list = "/home/gyf/pkg/conformer_new/asr_conformer/dataset/val_map_gt.txt"
    pack_files = []
    wav_pack = []
    with open(file_list, "r", encoding="utf-8") as fs:
        lines = fs.readlines()
        for line in lines:
            line = line.strip().split(" ")
            line.pop(-1)
            line.pop(-1)
            # line = " ".join(line)
            # pack_files.append(line)
            
            # print(line)
            for f in line:
                wav_pack.append(wav_dict[f])
            print(f'packing {wav_pack} to <packed/{os.path.basename(wav_pack[0])}>')
            pack_wavs(wav_pack, f"packed/{os.path.basename(wav_pack[0])}")
            wav_pack = []
    